﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.wjl;
using B.S.Sterilizationcenter.Domain.zyy;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.WJL;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.WJL
{
    public class AddCleanwatchCommandHanders : IRequestHandler<AddCleanwatchCommands, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public AddCleanwatchCommandHanders(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        } 

        /// <summary>
        /// 添加清洗记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AddCleanwatchCommands request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                int totalAffectedRows = 0;

                string Itembarcode = "WPTM" + DateTime.Now.ToString("yyyyMMddHHmmss");
                DateTime now = DateTime.Now;

                //开启事务
                db.Ado.BeginTran();
                try
                {
                    var cleanwatch = mapper.Map<Cleanwatch>(request);
                    cleanwatch.Itembarcode = Itembarcode;
                    cleanwatch.IsDelete = false;
                    cleanwatch.Status = 1;

                    var cleanId = await db.Insertable(cleanwatch).ExecuteReturnIdentityAsync();
                    if (cleanId <= 0)
                    {
                        db.Ado.RollbackTran();
                        return new ApiResult<int>
                        {
                            Code = ApiEnums.添加失败,
                            Msg = "添加失败",
                            Data = 0
                        };
                    }
                    totalAffectedRows++;

                    if (request.Createid != null && request.Createid.Any())
                    {
                        var items = await db.Queryable<ItemTable>().Where(x=>request.Createid.Contains(x.ItemId)&&!x.IsDelete).ToListAsync();

                        if(items.Any())
                        {
                            var cleanwatchItemed=items.Select(item=>new CleanwatchItemed
                            {
                                CleaningId = cleanId,
                                ItemId=item.ItemId,
                            }).ToList();

                            var itemAffectedRows=await  db.Insertable(cleanwatchItemed).ExecuteCommandAsync();
                            totalAffectedRows += itemAffectedRows;

                            if(totalAffectedRows <= 0)
                            {
                                db.Ado.RollbackTran();
                                return new ApiResult<int>
                                {
                                    Code = ApiEnums.添加失败,
                                    Msg = "回收物品关联保存失败",
                                    Data = 0
                                };
                            }
                        }
                    }

                    //提交事务
                    db.Ado.CommitTran();

                    result.Code = ApiEnums.添加成功;
                    result.Msg = $"成功保存回收信息及{totalAffectedRows - 1}条物品关联";
                    result.Data = totalAffectedRows;
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    db.Ado.RollbackTran();
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.添加失败,
                        Msg = $"保存回收信息时出错: {ex.Message}",
                        Data = 0
                    };
                }

                return result;
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.添加失败,
                    Msg = ex.Message,
                    Data = 0
                };
            }
        }
    }
}
